package io.dfjx.modules.auth.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

public class TokenUtils {

    public static String extractHeaderToken(HttpServletRequest request) {
        try {

            Enumeration<String> headers = request.getHeaders("cookie");
            while (headers.hasMoreElements()) {
                String value = headers.nextElement();
                if (value.contains(Auth2Constants.AUTH_ACCESS_TOKEN)) {
                    String accessToken = value.substring(value.indexOf("access_token="), value.indexOf("access_token=") + 55);
                    String authorization = accessToken.substring(13);
                    String authHeaderValue = handleToken(request, authorization);
                    if (authHeaderValue != null) {
                        return authHeaderValue;
                    }
                }

            }

            Enumeration<String> headersAUTHORIZATION = request.getHeaders(Auth2Constants.AUTH_AUTHORIZATION);
            while (headersAUTHORIZATION.hasMoreElements()) {
                String value = headersAUTHORIZATION.nextElement();
                String authorization = value.substring(7);

                StringBuffer mBuffer = new StringBuffer(authorization);

                if (!authorization.contains(Auth2Constants.AUTH_BEARER) && !authorization.contains("Basic")) {
                    StringBuffer bearer = mBuffer.insert(0, Auth2Constants.AUTH_BEARER);
                    authorization = bearer.toString();
                }

//                String redisAccessToken = redisUtil.get(authorization, String.class);
//
//                if (!StringUtils.isEmpty(redisAccessToken)) {
//                    authorization = redisAccessToken;
//                }

                String authHeaderValue = handleToken(request, authorization);
                if (authHeaderValue != null) {
                    return authHeaderValue;
                }
            }

        }catch (Exception e) {
            return null;
        }

        return null;
    }

    public static String handleToken(HttpServletRequest request, String authorization) {
        if ((authorization.toLowerCase().startsWith(Auth2Constants.AUTH_BEARER.toLowerCase()))) {
            String authHeaderValue = authorization.substring(Auth2Constants.AUTH_BEARER.length()).trim();
            // Add this here for the auth details later. Would be better to change the signature of this method.
            request.setAttribute("OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE",
                    authorization.substring(0, Auth2Constants.AUTH_BEARER.length()).trim());
            int commaIndex = authHeaderValue.indexOf(',');
            if (commaIndex > 0) {
                authHeaderValue = authHeaderValue.substring(0, commaIndex);
            }
            return authHeaderValue;
        }
        return null;
    }
}
